from channels.generic.websocket import AsyncWebsocketConsumer
from ocpp.routing import on
from ocpp.v201 import ChargePoint as cp
from ocpp.v201 import call_result, call
import json
from datetime import datetime


class ChargePointConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.cp = cp(self.scope['url_route']['kwargs']['charge_point_id'], self)
        await self.accept()

    async def disconnect(self, close_code):
        pass

    async def receive(self, text_data):
        message = json.loads(text_data)
        response = await self.cp.route_message(message)
        await self.send(json.dumps(response))

    async def send(self, message):
        await super().send(text_data=message)

    @on('BootNotification')
    async def on_boot_notification(self, charging_station, reason, **kwargs):
        # Handle BootNotification request and return a response.
        return call_result.BootNotificationPayload(
            current_time=datetime.utcnow().isoformat(),
            interval=10,
            status='Accepted',
        )
